﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;

namespace MassUtility
{
    public static class AlexaCheckRank
    {
        public static int getAlexa(String URL)
        {
            try
            {

          
            int AlexaRank = 0;
            WebRequest request = WebRequest.Create("http://data.alexa.com/data? cli=10&dat=snbamz&url=" + URL);
            WebResponse response = request.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream());
            string line = "";
            while ((line = sr.ReadLine()) != null)
            {
                if (line.ToUpper().Contains("POPULARITY"))
                {
                    Regex rankRegex = new Regex("TEXT=\"\\s*(.+)\"");
                    Match match = rankRegex.Match(line);
                    if (match.Success)
                    {
                        AlexaRank = int.Parse(match.Groups[1].Value);
                    }     
                }
               
            }
            sr.Close();
            return AlexaRank;
            }
            catch (Exception)
            {

                return -1;
            }
        }
        public static int getAlexa(String URL,string proxy)
        {
            int AlexaRank = 0;
            WebProxy p = null;
            p = new WebProxy(proxy);
            WebRequest.DefaultWebProxy = p;
            WebRequest request = WebRequest.Create("http://data.alexa.com/data? cli=10&dat=snbamz&url=" + URL);
            request.Proxy = p;
            WebResponse response = request.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream());
            string line = "";
            while ((line = sr.ReadLine()) != null)
            {
                if (line.ToUpper().Contains("POPULARITY"))
                {
                    Regex rankRegex = new Regex("TEXT=\"\\s*(.+)\"");
                    Match match = rankRegex.Match(line);
                    if (match.Success)
                    {
                        AlexaRank = int.Parse(match.Groups[1].Value);
                    }
                }

            }
            sr.Close();
            return AlexaRank;
        }
    }
}
